#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
sys.path.append('/usr/local/lib/python2.7/site-packages/')
sys.path.append('/usr/local/Cellar/chromedriver/2.36/bin')

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from PIL import Image
import time


def get_snap():
    '''
    对整个网页截图，保存成图片，然后用PIL.Image拿到图片对象
    :return: 图片对象
    '''
    driver.save_screenshot('snap.png')
    page_snap_obj = Image.open('snap.png')
    return page_snap_obj


def get_image():
    img = wait.until(EC.presence_of_element_located(
        (By.ID, 'tcaptcha_iframe')))
    time.sleep(2)  # 保证图片刷新出来
    # localtion = img.location
    # size = img.size

    # top = localtion['y']
    # bottom = localtion['y'] + size['height']
    # left = localtion['x']
    # right = localtion['x'] + size['width']
    top = 140
    bottom = 554
    left = 19 * 2
    right = 381 * 2
    page_snap_obj = get_snap()
    crop_imag_obj = page_snap_obj.crop((left, top, right, bottom))
    Lim = crop_imag_obj.convert('L')
    Lim.save('fun_Level.jpg')

    # setup a converting table with constant threshold
    threshold = 80
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)

    # convert to binary image by the table
    bim = Lim.point(table, '1')
    bim.save('fun_binary.jpg')
    # crop_imag_obj.save('a.png')
    return crop_imag_obj


def get_distance(image1, image2):
    '''
    拿到滑动验证码需要移动的距离
    :param image1:没有缺口的图片对象
    :param image2:带缺口的图片对象
    :return:需要移动的距离
    '''
    threshold = 60
    left = 57
    for i in range(left, image1.size[0]):
        for j in range(image1.size[1]):
            rgb1 = image1.load()[i, j]
            rgb2 = image2.load()[i, j]
            res1 = abs(rgb1[0] - rgb2[0])
            res2 = abs(rgb1[1] - rgb2[1])
            res3 = abs(rgb1[2] - rgb2[2])
            if not (res1 < threshold and res2 < threshold and res3 < threshold):
                return i - 7  # 经过测试，误差为大概为7
    return i - 7  # 经过测试，误差为大概为7


def get_tracks(distance):
    '''
    拿到移动轨迹，模仿人的滑动行为，先匀加速后匀减速
    匀变速运动基本公式：
    ①v=v0+at
    ②s=v0t+½at²
    ③v²-v0²=2as

    :param distance: 需要移动的距离
    :return: 存放每0.3秒移动的距离
    '''
    # 初速度
    v = 0
    # 单位时间为0.2s来统计轨迹，轨迹即0.2内的位移
    t = 0.3
    # 位移/轨迹列表，列表内的一个元素代表0.2s的位移
    tracks = []
    # 当前的位移
    current = 0
    # 到达mid值开始减速
    mid = distance * 4 / 5

    while current < distance:
        if current < mid:
            # 加速度越小，单位时间的位移越小,模拟的轨迹就越多越详细
            a = 2
        else:
            a = -3

        # 初速度
        v0 = v
        # 0.2秒时间内的位移
        s = v0 * t + 0.5 * a * (t**2)
        # 当前的位置
        current += s
        # 添加到轨迹列表
        tracks.append(round(s))

        # 速度已经达到v,该速度作为下次的初速度
        v = v0 + a * t
    return tracks


driver = None
try:
    options = webdriver.ChromeOptions()
    options.add_argument('lang=zh_CN.UTF-8')
    options.add_argument('headless')
    options.add_argument(
        'user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"')
    driver = webdriver.Chrome(chrome_options=options)
    driver.set_window_size(400, 800)
    driver.get('https://weixin110.qq.com/security/readtemplate?t=login_verify_entrances/w_tcaptcha&wechat_real_lang=zh_CN&aid=2000000038&clientype=1&lang=2052&apptype=undefined&captype=7&disturblevel=1&secticket=3_91477636029866066144557203060825')
    wait = WebDriverWait(driver, 5)

    # 步骤一：先点击按钮，弹出没有缺口的图片
    # button=wait.until(EC.presence_of_element_located((By.CLASS_NAME,'geetest_radar_tip')))
    # button.click()

    # 步骤二：拿到没有缺口的图片
    image1 = get_image()
    print 'ok'
    # import time
    # time.sleep(200)
except Exception as e:
    print e
finally:
    driver.close()
